# _*_ encoding:utf-8 _*_
import json

from django_redis import get_redis_connection
from meiduo_mall.utils.cookiesecret import CookieSecret


def merge_cart_cookie_to_redis(request, response):
    """
    登录后合并cookie购物车数据到Redis
    :param request: 本次请求对象，获取cookie中的数据
    :param response: 本次响应对象，清除cookie中的数据
    :return: response
    """

    # 1. 提取cookie购物车数据
    cookie_str = request.COOKIES.get('carts')
    if cookie_str:
        cart_dict = CookieSecret.loads(cookie_str)
    else:
        cart_dict = {}

    # 2. 把cookie购物车数据合并到redis中
    user = request.user
    conn = get_redis_connection('carts')

    sku_ids = cart_dict.keys()
    for sku_id in sku_ids:
        # 2.1 商品数量
        conn.hset(f'carts_{user.id}', sku_id, cart_dict[sku_id]['count'])

        # 2.2 选中状态
        selected = cart_dict[sku_id]['selected']
        if selected:
            conn.sadd(f'selected_{user.id}', sku_id)
        else:
            conn.srem(f'selected_{user.id}', sku_id)

    # 3. 清除cookie
    response.delete_cookie('carts')

    return response
